package com.example.springsecuritydemo.service.impl;

import com.example.springsecuritydemo.config.DBUserDetailsManager;
import com.example.springsecuritydemo.entity.User;
import com.example.springsecuritydemo.mapper.UserMapper;
import com.example.springsecuritydemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DBUserDetailsManager dbUserDetailsManager;
    
    /**
     * 根据用户名查询用户信息
     * @param username 用户名
     * @return 用户实体对象
     */
    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }
    
    /**
     * 查询所有用户
     * @return 用户列表
     */
    @Override
    public List<User> selectAll() {
        return userMapper.selectAll();
    }
    
    /**
     * 新增用户
     * @param user 用户实体对象
     * @return 受影响的行数
     */
    @Override
    public int insert(User user) {
        return userMapper.insert(user);
    }
    
    /**
     * 更新用户信息
     * @param user 用户实体对象
     * @return 受影响的行数
     */
    @Override
    public int update(User user) {
        return userMapper.update(user);
    }
    
    /**
     * 根据用户ID删除用户
     * @param id 用户ID
     * @return 受影响的行数
     */
    @Override
    public int deleteById(Integer id) {
        return userMapper.deleteById(id);
    }

    @Override
    public void saveUserDetails(User user) {
        // 创建包含默认权限的UserDetails对象
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        
        
        UserDetails userDetails = org.springframework.security.core.userdetails.User
                .withDefaultPasswordEncoder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities(authorities)
                .build();
        dbUserDetailsManager.createUser(userDetails);
    }
}